package com.shy.configs.common.clients;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisClient {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void setHashValue(String key, Map<String, String> data, int timeout, TimeUnit timeUnit) {
        stringRedisTemplate.opsForHash().putAll(key, data); // 存储数据
        if (timeout > 0) {
            stringRedisTemplate.expire(key, timeout, timeUnit); // 设置过期时间
        }
    }

    public String getField(String key, String field) {
        return (String) stringRedisTemplate.opsForHash().get(key, field);
    }

    /**
     * Redis的string类型
     *
     * @param key
     * @param value
     */
    public void setValue(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    /**
     * 读取某个key的value值
     *
     * @param key
     * @return
     */
    public String getValue(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    public boolean deleteKey(String tokenKey) {
        Boolean delete = stringRedisTemplate.delete(tokenKey);
        if (delete == null) {
            return false;
        }
        return delete.booleanValue();
    }
}
